<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 数据概览卡片 -->
      <el-col :span="24">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>数据概览</span>
              <el-button type="primary" link @click="refreshData">刷新数据</el-button>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="data-card">
                <div class="data-icon blue">
                  <el-icon><VideoPlay /></el-icon>
                </div>
                <div class="data-info">
                  <div class="data-title">总解析次数</div>
                  <div class="data-value">{{ statsData.totalParseCount }}</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="data-card">
                <div class="data-icon green">
                  <el-icon><User /></el-icon>
                </div>
                <div class="data-info">
                  <div class="data-title">用户数量</div>
                  <div class="data-value">{{ statsData.userCount }}</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="data-card">
                <div class="data-icon orange">
                  <el-icon><Calendar /></el-icon>
                </div>
                <div class="data-info">
                  <div class="data-title">今日解析</div>
                  <div class="data-value">{{ statsData.todayParseCount }}</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="data-card">
                <div class="data-icon purple">
                  <el-icon><VideoCamera /></el-icon>
                </div>
                <div class="data-info">
                  <div class="data-title">支持平台数</div>
                  <div class="data-value">{{ statsData.platformCount }}</div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>

      <!-- 解析趋势图 -->
      <el-col :span="16">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>解析趋势</span>
              <el-radio-group v-model="trendTimeRange" size="small" @change="handleTrendRangeChange">
                <el-radio-button label="week">近7天</el-radio-button>
                <el-radio-button label="month">近30天</el-radio-button>
                <el-radio-button label="year">近一年</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container">
            <div id="trendChart" style="width: 100%; height: 350px;"></div>
          </div>
        </el-card>
      </el-col>

      <!-- 平台分布图 -->
      <el-col :span="8">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>平台分布</span>
            </div>
          </template>
          <div class="chart-container">
            <div id="platformChart" style="width: 100%; height: 350px;"></div>
          </div>
        </el-card>
      </el-col>

      <!-- 热门视频排行 -->
      <el-col :span="12">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>热门视频排行</span>
            </div>
          </template>
          <el-table :data="hotVideos" style="width: 100%">
            <el-table-column type="index" label="排名" width="60" />
            <el-table-column label="视频标题" prop="title" :show-overflow-tooltip="true" />
            <el-table-column label="平台" prop="platform" width="100" />
            <el-table-column label="解析次数" prop="parseCount" width="100" sortable />
            <el-table-column label="操作" width="100" align="center">
              <template #default="scope">
                <el-button type="primary" link @click="handleViewVideo(scope.row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 活跃用户排行 -->
      <el-col :span="12">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>活跃用户排行</span>
            </div>
          </template>
          <el-table :data="activeUsers" style="width: 100%">
            <el-table-column type="index" label="排名" width="60" />
            <el-table-column label="用户名" prop="username" />
            <el-table-column label="解析次数" prop="parseCount" width="100" sortable />
            <el-table-column label="最近解析时间" prop="lastParseTime" width="180" />
            <el-table-column label="操作" width="100" align="center">
              <template #default="scope">
                <el-button type="primary" link @click="handleViewUser(scope.row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 查看视频详情对话框 -->
    <el-dialog :title="'视频详情 - ' + (currentVideo.title || '')" v-model="videoDialogVisible" width="800px" append-to-body>
      <div class="view-container" v-if="currentVideo">
        <div class="video-info">
          <div class="video-meta">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="视频标题">{{ currentVideo.title }}</el-descriptions-item>
              <el-descriptions-item label="视频平台">{{ currentVideo.platform }}</el-descriptions-item>
              <el-descriptions-item label="作者">{{ currentVideo.author }}</el-descriptions-item>
              <el-descriptions-item label="解析次数">{{ currentVideo.parseCount }}</el-descriptions-item>
              <el-descriptions-item label="首次解析时间">{{ currentVideo.firstParseTime }}</el-descriptions-item>
              <el-descriptions-item label="最近解析时间">{{ currentVideo.lastParseTime }}</el-descriptions-item>
            </el-descriptions>
          </div>
          
          <div class="video-cover" v-if="currentVideo.cover">
            <h4>视频封面</h4>
            <el-image 
              :src="currentVideo.cover" 
              style="max-width: 100%; max-height: 300px"
              :preview-src-list="[currentVideo.cover]"
            />
          </div>
          
          <div class="video-player" v-if="currentVideo.playUrl">
            <h4>视频播放</h4>
            <video 
              controls 
              :src="currentVideo.playUrl" 
              style="width: 100%; max-height: 400px;"
            ></video>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 查看用户详情对话框 -->
    <el-dialog :title="'用户详情 - ' + (currentUser.username || '')" v-model="userDialogVisible" width="800px" append-to-body>
      <div class="view-container" v-if="currentUser">
        <div class="user-info">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="用户名">{{ currentUser.username }}</el-descriptions-item>
            <el-descriptions-item label="昵称">{{ currentUser.nickname }}</el-descriptions-item>
            <el-descriptions-item label="解析次数">{{ currentUser.parseCount }}</el-descriptions-item>
            <el-descriptions-item label="注册时间">{{ currentUser.createTime }}</el-descriptions-item>
            <el-descriptions-item label="最近解析时间">{{ currentUser.lastParseTime }}</el-descriptions-item>
            <el-descriptions-item label="最近登录时间">{{ currentUser.lastLoginTime }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="user-parse-history">
          <h4>最近解析记录</h4>
          <el-table :data="userParseHistory" style="width: 100%">
            <el-table-column label="视频标题" prop="title" :show-overflow-tooltip="true" />
            <el-table-column label="平台" prop="platform" width="100" />
            <el-table-column label="解析时间" prop="parseTime" width="180" />
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import { VideoPlay, User, Calendar, VideoCamera } from '@element-plus/icons-vue'
import { getParseStats } from '@/api/video/parse'
import * as echarts from 'echarts/core'
import { BarChart, LineChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

// 注册必须的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  BarChart,
  LineChart,
  PieChart,
  CanvasRenderer
])

// 图表实例
let trendChart = null
let platformChart = null

// 趋势图时间范围
const trendTimeRange = ref('week')

// 统计数据
const statsData = reactive({
  totalParseCount: 0,
  userCount: 0,
  todayParseCount: 0,
  platformCount: 0
})

// 热门视频数据
const hotVideos = ref([])

// 活跃用户数据
const activeUsers = ref([])

// 当前查看的视频
const currentVideo = ref({})
const videoDialogVisible = ref(false)

// 当前查看的用户
const currentUser = ref({})
const userDialogVisible = ref(false)
const userParseHistory = ref([])

// 获取统计数据
const getStatsData = async () => {
  try {
    const res = await getParseStats()
    if (res.code === 200) {
      const data = res.data
      
      // 更新统计数据
      statsData.totalParseCount = data.totalParseCount
      statsData.userCount = data.userCount
      statsData.todayParseCount = data.todayParseCount
      statsData.platformCount = data.platformCount
      
      // 更新热门视频
      hotVideos.value = data.hotVideos || []
      
      // 更新活跃用户
      activeUsers.value = data.activeUsers || []
      
      // 初始化图表
      initTrendChart(data.parseTrend || [])
      initPlatformChart(data.platformDistribution || [])
    }
  } catch (error) {
    console.error('获取统计数据失败', error)
    ElMessage.error('获取统计数据失败')
  }
}

// 初始化趋势图
const initTrendChart = (data) => {
  if (!trendChart) {
    trendChart = echarts.init(document.getElementById('trendChart'))
  }
  
  const xAxisData = data.map(item => item.date)
  const seriesData = data.map(item => item.count)
  
  const option = {
    title: {
      text: '视频解析趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '解析次数',
        type: 'line',
        smooth: true,
        data: seriesData,
        itemStyle: {
          color: '#409EFF'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(64, 158, 255, 0.7)'
            },
            {
              offset: 1,
              color: 'rgba(64, 158, 255, 0.1)'
            }
          ])
        }
      }
    ]
  }
  
  trendChart.setOption(option)
}

// 初始化平台分布图
const initPlatformChart = (data) => {
  if (!platformChart) {
    platformChart = echarts.init(document.getElementById('platformChart'))
  }
  
  const option = {
    title: {
      text: '平台分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      top: 'center',
      data: data.map(item => item.name)
    },
    series: [
      {
        name: '解析次数',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data.map(item => ({
          value: item.count,
          name: item.name
        }))
      }
    ]
  }
  
  platformChart.setOption(option)
}

// 处理趋势图时间范围变化
const handleTrendRangeChange = () => {
  // 这里可以根据选择的时间范围重新获取数据
  getStatsData()
}

// 刷新数据
const refreshData = () => {
  getStatsData()
  ElMessage.success('数据已刷新')
}

// 查看视频详情
const handleViewVideo = (row) => {
  currentVideo.value = row
  videoDialogVisible.value = true
}

// 查看用户详情
const handleViewUser = (row) => {
  currentUser.value = row
  // 这里可以获取用户的解析历史记录
  userParseHistory.value = [] // 模拟数据，实际应该从API获取
  userDialogVisible.value = true
}

// 窗口大小变化时重新调整图表大小
const handleResize = () => {
  trendChart && trendChart.resize()
  platformChart && platformChart.resize()
}

onMounted(() => {
  getStatsData()
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  trendChart && trendChart.dispose()
  platformChart && platformChart.dispose()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.box-card {
  width: 100%;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.data-card {
  display: flex;
  align-items: center;
  padding: 10px;
  border-radius: 4px;
  background-color: #f8f8f8;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 100px;
}

.data-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 15px;
  
  .el-icon {
    font-size: 30px;
    color: white;
  }
  
  &.blue {
    background-color: #409EFF;
  }
  
  &.green {
    background-color: #67C23A;
  }
  
  &.orange {
    background-color: #E6A23C;
  }
  
  &.purple {
    background-color: #909399;
  }
}

.data-info {
  flex: 1;
  
  .data-title {
    font-size: 14px;
    color: #606266;
    margin-bottom: 5px;
  }
  
  .data-value {
    font-size: 24px;
    font-weight: bold;
    color: #303133;
  }
}

.chart-container {
  width: 100%;
  height: 350px;
}

.view-container {
  .video-meta, .user-info {
    margin-bottom: 20px;
  }
  
  .video-cover {
    margin-bottom: 20px;
    
    h4 {
      margin-top: 0;
      margin-bottom: 10px;
    }
  }
  
  .video-player {
    margin-bottom: 20px;
    
    h4 {
      margin-top: 0;
      margin-bottom: 10px;
    }
  }
  
  .user-parse-history {
    h4 {
      margin-top: 0;
      margin-bottom: 10px;
    }
  }
}
</style>